package org.mx.spring.config;

import org.mx.spring.i18n.I18nResourceBundleFactory;
import org.mx.spring.i18n.I18nService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

/**
 * 描述： I18N 配置类
 *
 * @author john peng
 * Date time 2019/7/24 10:14 PM
 */
public class SpringI18nConfig {
    /**
     * 创建可重载的资源包消息工厂，该工厂目前支持从Properties文件或DS自定义资源表中加载资源
     *
     * @param env     Spring IoC容器上下文环境
     * @param context Spring IoC容器上下文
     * @return 可重载的资源包工厂
     */
    @ConditionalOnExpression("'${i18n.providers}'.length() > 0")
    @Bean(name = "i18nResourceBundleFactory", initMethod = "init", destroyMethod = "destroy")
    public I18nResourceBundleFactory i18nResourceBundleFactory(Environment env, ApplicationContext context) {
        return new I18nResourceBundleFactory(env, context);
    }

    /**
     * 创建i18n服务
     *
     * @param factory 可重载的资源包工厂
     * @return i18n服务
     */
    @ConditionalOnBean(I18nResourceBundleFactory.class)
    @Bean("i18nService")
    public I18nService i18nService(I18nResourceBundleFactory factory) {
        return new I18nService(factory);
    }
}
